#!/bin/bash

#作者 谢涛
echo
echo "你又要重启了吗，让我们开始吧！"
echo "当前目录下的jar包: "
echo
#找出当前目录下的jar文件
jars=()
i=0
for file in `find . -name '*.jar'`; do
	let i++
	jars[i]=${file#*/}
	echo $i: ${file#*/}
done
echo
echo -n "请输入要重启的jar文件序号（多个序号用逗号隔开）："
read index


#根据逗号把输入的下标拆分为数组
OLD_IFS=”$IFS”
IFS=”,”
arr=($index)
IFS=”$OLD_IFS”

echo
echo -n "启动环境选择(开发/测试/生产)输入prod: "
read config

if [ ! $config ] || ( [ "prod" !=  "$config" ] ); then
	echo "输入错误，退出"
	exit 0
fi

echo
echo -n "启动所占内存(推荐: 256/512/1024/2048等)输入数字（单位 m）："
read ram_size

case $ram_size in 
  [1-9][0-9]*)  
    ;; 
  *)  
  echo "启动内存输入必须是数字，退出"
  exit 0
    ;; 
esac 

if [ $ram_size -lt 256 ] ; then
	echo "启动内存不能小于256，退出"
	exit 0
fi

echo
echo -n $jarname"将要被重启，请确认，输入y/n："
read confirm 

#遍历要启动的文件
for i in ${arr[@]};do
jarname=${jars[$i]}

if [ "y" != $confirm ] || [ ! $confirm ]; then
	echo "退出"
	exit 0
fi

if [ ! -e $jarname ] || [ ! $jarname ]; then
	echo "错误：当前目录下没有找到$jarname"
	exit 1
fi

#停止
echo
echo "Stopping: " $jarname
PID=$(ps -ef | grep $jarname | grep -v grep | awk '{ print $2 }')
if [ -z "$PID" ]; then
    echo $jarname " : Application is already stopped"
else
    echo "kill 线程 :" $PID
    kill -9 $PID
    sleep 1
fi
#启动
echo "Starting: " $jarname
nohup java -jar -Xms${ram_size}m -Xmx${ram_size}m $jarname --spring.profiles.active=$config >/dev/null 2>&1 &
#nohup java -jar $jarname --spring.profiles.active=$config >/dev/null 2>&1 &

echo "已重启$jarname，请去查看日志确认"
done
